import functools
import os
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import distutils2_version as version
import simplejson as json
import jinja2


SERVER_SOFTWARE = os.environ.get('SERVER_SOFTWARE')
if SERVER_SOFTWARE is None:
    DEBUG = True
elif SERVER_SOFTWARE.startswith('Dev'):
    DEBUG = True
else:
    DEBUG = False
del SERVER_SOFTWARE

template_loader = jinja2.FileSystemLoader('templates')
template_env = jinja2.Environment(loader=template_loader)


def normalized_version(version_str):
    """Convert a version number to a NormalizedVersion instance.

    In cases where the version cannot be converted, use 0.0 as the version.

    """
    normalized = version.suggest_normalized_version(version_str)
    if normalized:
        return version.NormalizedVersion(normalized)
    else:
        return version.NormalizedVersion('0.0')


cache_len = 3600 if not DEBUG else 10


def memcache_get(fxn):
    """Decorator to try to get the information from memcache before doing the
    actual GET request."""
    @functools.wraps(fxn)
    def get(self, *args, **kwargs):
        assert not self.request.query_string
        key = self.request.path
        cached = memcache.get(key)
        if cached is not None:
            self.response.out.write(cached)
        else:
            fxn(self, *args, **kwargs)
            memcache.add(key, self.response.out.getvalue(), cache_len)

    return get

def cache_control(fxn):
    """Decorator to use the HTTP Cache-Control header."""
    @functools.wraps(fxn)
    def get(self, *args, **kwargs):
        fxn(self, *args, **kwargs)
        self.response.headers.add_header('Cache-Control',
                                         'max-age=%s' % cache_len)

    return get


class Handler(webapp.RequestHandler):

    """Base class for handlers."""

    def request_json(self, name):
        """Return the data found in the request in the 'name' argument,
        converted from JSON."""
        data = self.request.get(name)
        if data:
            return json.loads(data)
        else:
            return None

    def json_dict(self, convert):
        """Convert a dict's values into JSON values."""
        for key, value in convert.iteritems():
            convert[key] = json.dumps(value)


class MainHandler(webapp.RequestHandler):

    @cache_control
    @memcache_get
    def get(self):
        template = template_env.get_template('home.html')
        self.response.out.write(template.render())


def main():
    import metrics
    application = webapp.WSGIApplication([('/', MainHandler)],
                                         debug=DEBUG)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
